package com.lntea.netty.demo.diff.echo.aio;

import com.lntea.netty.demo.diff.echo.EchoConstant;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

/**
 * Title: AioEchoServerHandler.java<br>
 * Description:  <br>
 * Copyright: Copyright (c) 2015<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author lichao
 * @date 2019/11/5 17:40
 */
public class AioEchoServerHandler implements Runnable {

    /** 计数器 */
    private CountDownLatch latch;
    /** 异步服务端通道 */
    private AsynchronousServerSocketChannel assc;

    public AioEchoServerHandler() {
        try {
            // 1. 打开异步服务端通道
            assc = AsynchronousServerSocketChannel.open();
            // 2. 绑定ip和端口
            assc.bind(new InetSocketAddress(EchoConstant.SERVER_IP, EchoConstant.SERVER_PORT));
            System.out.println(String.format("Echo Server start at port %d", EchoConstant.SERVER_PORT));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doAccept() {
        assc.accept(this, new AcceptCompletionHandler());
    }

    public AsynchronousServerSocketChannel getAsynchronousServerSocketChannel() {
        return assc;
    }

    public CountDownLatch getLatch() {
        return latch;
    }
}
